const errorType = require('../constants/error-types')
const { getUserByName } = require('../service/user-service')
const { checkWeblog } = require('../service/auth-service')
const jwt = require('jsonwebtoken')
const { PUBLIC_KEY } = require('../app/config')

// 验证登录
const verifyLogin = async (ctx, next) => {
  // 1、判断用户名和密码是否为空
  const { username, password } = ctx.request.body
  if (!username || !password) {
    const error = new Error(errorType.USRENAME_OR_PASSWORD_IS_EMPTY)
    return ctx.app.emit('error', error, ctx)
  }
  // 2、判断用户名是否存在
  const result = await getUserByName(username)
  if (!result.length) {
    const error = new Error(errorType.USRENAME_IS_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  // 3、判断密码是否正确
  if (password !== result[0].password) {
    const error = new Error(errorType.PASSWORD_IS_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  ctx.user = result[0]
  await next()
}

// 验证授权
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware")
  const { authorization } = ctx.request.headers
  if (!authorization) {
    const error = new Error(errorType.UNAUTHRORIZATION)
    return ctx.app.emit('error', error, ctx)
  }
  const token = authorization.replace('Bearer ', '')
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256']
    })
    ctx.user = result
    await next()
  } catch (err) {
    const error = new Error(errorType.UNAUTHRORIZATION)
    ctx.app.emit('error', error, ctx)
  }
}

// 验证权限
const verifyPermission = async (ctx, next) => {
  console.log("验证权限的middleware")
  // 注意params参数格式 例如 weblogId
  const [ resourceKey ] = Object.keys(ctx.params)
  console.log(Object.keys(ctx.params))
  // 表名
  const tableName = resourceKey.replace("Id", '')
  // 表的id值
  const resourceId = ctx.params[resourceKey]
  const userId = ctx.user.id
  const result = await checkWeblog(tableName, resourceId, userId)
  if (!result.length) {
    const error = new Error(errorType.UNPREMISSION)
    return ctx.app.emit("error", error, ctx)
  }
  await next()
}

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission
}